package com.handu.luna.boss.controller;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.LinkedList;
import java.util.List;

import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.handu.luna.core.domain.goods.Brand;
import com.handu.luna.core.domain.goods.Goods;
import com.handu.luna.core.domain.promotion.Activities;
import com.handu.luna.core.domain.promotion.Activities.ActivitiesMethods;
import com.handu.luna.core.domain.promotion.Activities.ActivitiesRange;
import com.handu.luna.core.domain.search.ActivitiesSearch;
import com.handu.luna.core.domain.search.GoodsSearchCondition;
import com.handu.luna.core.domain.user.UserRank;


@Controller
@RequestMapping("/promotion/activities/*")
public class ActivitiesController extends BaseController{
	
	@RequestMapping(value = "index",method = RequestMethod.GET)
	public BossModel index(String viewState,@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable)throws UnsupportedEncodingException {

		ActivitiesSearch search = null;
		if(viewState != null && !viewState.trim().equals("")){
			//解析传递过来的查询json字符串
			search = (ActivitiesSearch)JSONObject.toBean(JSONObject.fromObject(new String(Base64.getUrlDecoder().decode(viewState),"UTF-8")), ActivitiesSearch.class);
			
			return createModel("/promotion/activities/index")
					.add("activitiesSearch", search)
					.add("activitiesPage",context.getActivitiesRepository().findAll(Activities.selectCondition(search), pageable))
					.add("viewState", viewState);
		}else{
			search = new ActivitiesSearch();
			return createModel("/promotion/activities/index")
					.add("activitiesSearch", search)
					.add("activitiesPage",context.getActivitiesRepository().findAll(pageable))
					.add("viewState", "");
		}
	}
	
	@RequestMapping(value = "index",method = RequestMethod.POST)
    public BossModel index(ActivitiesSearch activitiesSearch,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable) throws UnsupportedEncodingException{

		return createModel()
				.add("activitiesPage",context.getActivitiesRepository().findAll(Activities.selectCondition(activitiesSearch),pageable))
				.add("activitiesSearch", activitiesSearch)
				.add("viewState", Base64.getUrlEncoder().encodeToString(JSONObject.fromObject(activitiesSearch).toString().getBytes("UTF-8")));

	}
	
	@RequestMapping(value="add")
	public BossModel add(int page , String viewState){
		Activities activities = new Activities();
		LinkedList<UserRank> userRank = new LinkedList<UserRank>(context.getUserRankRepository().findAllNotSpecial());
		LinkedList<Brand> brands = new LinkedList<Brand>(context.getBrandRepository().findAll());
		Brand brand = new Brand();
		brand.setId(0l);
		brand.setName("请选择品牌");
		brands.add(0,brand);
		GoodsSearchCondition searchCondition = new GoodsSearchCondition(GoodsSearchCondition.SearchType.ACTIVITIES);
		return createModel("promotion/activities/info")
				.add("activities",activities)
				.add("userRanks", userRank)
				.add("searchBrands", context.getBrandRepository().findAll())
				.add("categorys", context.getCategoryRepository().findAll())
				.add("brands", brands)
				.add("activitiesRange", Activities.ActivitiesRange.values())
				.add("activitiesMethods", Activities.ActivitiesMethods.values())
				.add("selectableGoods", context.getGoodsRepository().findAll(searchCondition.searchabledGoods(searchCondition)))
				.add("page",page)
                .add("viewState",(viewState==null?"":viewState));
	}
	
	@RequestMapping(value = "edit/{id}")
    public BossModel edit(@PathVariable long id,int page,String viewState){
	 LinkedList<UserRank> userRank = new LinkedList<UserRank>(context.getUserRankRepository().findAllNotSpecial());
	 LinkedList<Brand> brands = new LinkedList<Brand>(context.getBrandRepository().findAll());
	 Brand brand = new Brand();
	 brand.setId(0l);
	 brand.setName("请选择品牌");
	 brands.add(0,brand);
	 GoodsSearchCondition searchCondition = new GoodsSearchCondition(id,GoodsSearchCondition.SearchType.ACTIVITIES);
	 Activities activities = context.getActivitiesRepository().findOne(id);
        return createModel("promotion/activities/info")
                .add("activities",activities)
                .add("activitiesRangeValue", activities.getActivitiesRange())
                .add("activitiesMethodsValue", activities.getActivitiesMethods())
                .add("userRanks", userRank)
				.add("categorys", context.getCategoryRepository().findAll())
				.add("brands", brands)
				.add("searchBrands", context.getBrandRepository().findAll())
				.add("activitiesRange", Activities.ActivitiesRange.values())
				.add("activitiesMethods", Activities.ActivitiesMethods.values())
                .add("selectableGoods", context.getGoodsRepository().findAll(searchCondition.searchabledGoods(searchCondition)))
                .add("page",page)
                .add("viewState",viewState);
    }
	
	@RequestMapping(value = "buygeiveGoodsSearch",method = RequestMethod.POST)
    public @ResponseBody JSONArray buygeiveGoodsSearch(String goodsCategoryId,String goodsBrandsId,String goodsName ){
        List<Goods> list = context.getGoodsRepository().findAll(new Goods().searchBuygiveGoods(goodsCategoryId,goodsBrandsId,goodsName));
        StringBuffer buffer = new StringBuffer("[");
        if(CollectionUtils.isNotEmpty(list)){
            for (Goods goods:list){
                buffer.append("{\"id\":\""+goods.getId()+"\",\"name\":\""+goods.getName()+"\"},");
            }
        }
        if (buffer.length()>1){
            buffer.deleteCharAt(buffer.length()-1);
        }
        buffer.append("]");
        return JSONArray.fromObject(buffer.toString());
    }
	
	@RequestMapping(value = "save",method = RequestMethod.POST)
    @InitBinder(value = {"activitiesName","beginTime","endTime","userRank","activitiesRange","brands","categorys","activitiesGoodsids","minAmount","maxAmount","activitiesMethods","methodsExt","methodsGoodsids"})
    public BossModel save(@Valid Activities activities,final BindingResult bindingResult,RedirectAttributes redirectAttributes,int page,String viewState){
		
		if (bindingResult.hasErrors()) {
			LinkedList<Brand> brands = new LinkedList<Brand>(context.getBrandRepository().findAll());
			Brand brand = new Brand();
			brand.setId(0l);
			brand.setName("请选择品牌");
			brands.add(0,brand);
			GoodsSearchCondition searchCondition = new GoodsSearchCondition(GoodsSearchCondition.SearchType.ACTIVITIES);
            return createModel("promotion/activities/info")
                    .add("activities",activities)
                    .add("selectableGoods", context.getGoodsRepository().findAll(searchCondition.searchabledGoods(searchCondition)))
                    .add("userRanks", context.getUserRankRepository().findAllNotSpecial())
                    .add("categorys", context.getCategoryRepository().findAll())
                    .add("brands", brands);
        }
		
		if(activities.getActivitiesRange() == ActivitiesRange.ALL){
			activities.setBrands(0);
			activities.setCategorys("");
			activities.setActivitiesGoodsids("");
		}else if(activities.getActivitiesRange() == ActivitiesRange.CATBRAND){
			activities.setActivitiesGoodsids("");
		}else if(activities.getActivitiesRange() == ActivitiesRange.GOODS){
			activities.setBrands(0);
			activities.setCategorys("");
		}
		if(!(activities.getActivitiesMethods() == ActivitiesMethods.BUYGIVE)){
			activities.setMethodsGoodsids("");
		}
        String message = "";
        if(null==activities.getId() || activities.getId() == 0){
            message = "添加活动"+activities.getActivitiesName()+ "成功";
        }else{
            message = "修改活动"+activities.getActivitiesName()+ "成功";
        }
        if (!(activities.getId()==null||activities.getId()==0)){
            redirectAttributes.addAttribute("page",page);
            redirectAttributes.addAttribute("viewState",StringUtils.isNotBlank(viewState)?viewState:"");
        }
        if(activities.isNew()){
        	context.getActivitiesRepository().save(activities);
        }else{
        	activities.update();
        }
        redirectAttributes.addFlashAttribute("message", message);
        return createModel("redirect:index");
    }
	
	@RequestMapping(value = "delete",method = RequestMethod.POST)
    public BossModel delete(long id,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable,String viewState) throws UnsupportedEncodingException{
		context.getActivitiesRepository().delete(id);
		ActivitiesSearch search = null;
		if(viewState != null && !viewState.trim().equals("")){
			//解析传递过来的查询json字符串
			search = (ActivitiesSearch)JSONObject.toBean(JSONObject.fromObject(new String(Base64.getUrlDecoder().decode(viewState),"UTF-8")), ActivitiesSearch.class);
			
			return createModel("/promotion/activities/activities_table")
					.add("activitiesSearch", search)
					.add("activitiesPage",context.getActivitiesRepository().findAll(Activities.selectCondition(search), pageable))
					.add("viewState", viewState);
		}else{
			search = new ActivitiesSearch();
			return createModel("/promotion/activities/activities_table")
					.add("activitiesSearch", search)
					.add("activitiesPage",context.getActivitiesRepository().findAll(pageable))
					.add("viewState", "");
		}
		
	}

}
